//
//  MAPYSaveManager.swift
//  Mars Proxy
//
//  Created by PowerfullClean on 2023/10/16.
//

import UIKit
import CoreData

extension MAPYManager {
    func mapy_createDataBase() {
        mapy_storeManager.loadPersistentStores { _, mapy_error in
            if mapy_error == nil {
                let mapy_serverModels = self.mapy_getAllServerModels()
                if mapy_serverModels.count == 0 {
                let mapy_model = self.mapy_createServerModel(mapy_country:"US", mapy_address: "195.234.82.185", mapy_password: "KwmurbWXx.DZVBk6", mapy_port: "1627", mapy_smart: true)
                    mapy_model.mapy_select = true
                    self.mapy_updateDataModel()
                }
                return
            }
            
        }
        
    }
    func mapy_updateDataModel() {
        let mapy_context = mapy_storeManager.viewContext
        do {
            if mapy_context.hasChanges {
                try mapy_context.save()
            }
        } catch {
            debugPrint("\(error)")
        }
    }
    func mapy_rollBackDataModel() {
        let mapy_context = mapy_storeManager.viewContext
        mapy_context.rollback()
    }
    
}
//MARK: - mapy server
extension MAPYManager {
    @discardableResult func mapy_createServerModel(mapy_country:String = "", mapy_address: String = "", mapy_password: String = "KwmurbWXx.DZVBk6", mapy_port: String = "1627", mapy_method: String = "chacha20-ietf-poly1305", mapy_smart: Bool = false) -> MAPYServerModel {
        let mapy_context = mapy_storeManager.viewContext
        let mapy_serverModel = NSEntityDescription.insertNewObject(forEntityName: "MAPYServerModel",
                                                                   into: mapy_context) as! MAPYServerModel
        
        mapy_serverModel.mapy_address = mapy_address
        mapy_serverModel.mapy_password = mapy_password
        mapy_serverModel.mapy_port = mapy_port
        mapy_serverModel.mapy_method = mapy_method
        mapy_serverModel.mapy_smart = mapy_smart
        mapy_serverModel.mapy_country = mapy_country
        mapy_serverModel.mapy_icon = "mapy_list_icon"
        if mapy_country == "United States" {
            mapy_serverModel.mapy_icon = "mapy_list_us"
        }
        if mapy_country == "United Kingdom" {
            mapy_serverModel.mapy_icon = "mapy_list_en"
        }
        if mapy_country == "Canada" {
            mapy_serverModel.mapy_icon = "mapy_list_ca"
        }
        if mapy_smart {
            mapy_serverModel.mapy_icon = "mapy_home_changeIcon"
            mapy_serverModel.mapy_country = "Auto choose"
        }
        if mapy_context.hasChanges {
            do {
                try mapy_context.save()
            } catch {
                
            }
        }
        return mapy_serverModel
    }
    func mapy_getAllServerModels() -> [MAPYServerModel] {
        let mapy_context = mapy_storeManager.viewContext
        let mapy_serverModel = NSFetchRequest<MAPYServerModel>(entityName: "MAPYServerModel")
        mapy_serverModel.predicate = NSPredicate(format: "mapy_smart == false")
        do {
            let mapy_serverModels = try mapy_context.fetch(mapy_serverModel)
            return mapy_serverModels
        } catch {
            
        }
        return [MAPYServerModel]()
    }
    func mapy_getSmartServerModel() -> MAPYServerModel? {
        let mapy_context = mapy_storeManager.viewContext
        let mapy_serverModel = NSFetchRequest<MAPYServerModel>(entityName: "MAPYServerModel")
        mapy_serverModel.predicate = NSPredicate(format: "mapy_smart == true")
        do {
            let mapy_serverModels = try mapy_context.fetch(mapy_serverModel)
            return mapy_serverModels.first
        } catch {
            
        }
        return nil
    }
    func mapy_getSelectServerModels() -> [MAPYServerModel] {
        let mapy_context = mapy_storeManager.viewContext
        let mapy_serverModel = NSFetchRequest<MAPYServerModel>(entityName: "MAPYServerModel")
        mapy_serverModel.predicate = NSPredicate(format: "mapy_select == true")
        do {
            let mapy_serverModels = try mapy_context.fetch(mapy_serverModel)
            return mapy_serverModels
        } catch {
            
        }
        return [MAPYServerModel]()
    }
    func mapy_getSelectServerModel() -> MAPYServerModel? {
        let mapy_context = mapy_storeManager.viewContext
        let mapy_serverModel = NSFetchRequest<MAPYServerModel>(entityName: "MAPYServerModel")
        mapy_serverModel.predicate = NSPredicate(format: "mapy_select == true")
        do {
            let mapy_serverModels = try mapy_context.fetch(mapy_serverModel)
            return mapy_serverModels.first
        } catch {
            
        }
        return nil
    }
    // 批量删除列表的ip 地址
    func mapy_deleteServeListModels() {
        let mapy_context = mapy_storeManager.newBackgroundContext()
        let mapy_model = NSFetchRequest<NSFetchRequestResult>(entityName: "MAPYServerModel")
        mapy_model.predicate = NSPredicate(format: "mapy_smart == false")
        let mapy_deltes = NSBatchDeleteRequest(fetchRequest: mapy_model)
        do {
            try mapy_context.execute(mapy_deltes)
            if mapy_context.hasChanges {
                try mapy_context.save()
            }
        } catch  {
            
        }
    }
}
//MARK: - mapy save serverModel
import Disk
//let mapy_vpn_response_key = "mapy_vpn_response_key"
let mapy_vpnResList1_key = "mapy_vpnResList1_key"
let mapy_vpnResList2_key = "mapy_vpnResList2_key"
let mapy_vpnSmartClick_key = "mapy_vpnSmartClick_key"
extension MAPYManager {
    func mapy_saveVPNRequestModel(mapy_vpnReqModel: MAPYVPNRequestModel, mapy_savePath: String = mapy_vpnResList1_key) {
        try? Disk.save(mapy_vpnReqModel, to: .caches, as: "\(mapy_savePath).json")
    }
    //    func mapy_getVPNRequestModel(mapy_savePath: String = mapy_vpnResList1_key) -> MAPYVPNRequestModel {
    //        guard (try? Disk.retrieve("\(mapy_savePath).json", from: .caches, as: MAPYVPNRequestModel.self)) != nil else { return MAPYVPNRequestModel() }
    //        return MAPYVPNRequestModel()
    //    }
    func mapy_getVPNRequestModel(mapy_savePath: String = mapy_vpnResList1_key) -> MAPYVPNRequestModel {
        var mapy_responseString = mapy_getSrValue(mapy_key: mapy_savePath)
        if mapy_responseString.count < 10 {
            return MAPYVPNRequestModel()
        }
        let startIndex = mapy_responseString.index(mapy_responseString.startIndex, offsetBy: 0)
        mapy_responseString.remove(at: startIndex)
        mapy_responseString.remove(at: startIndex)
        let endIndex = mapy_responseString.index(mapy_responseString.endIndex, offsetBy: -5)
        mapy_responseString = String(mapy_responseString[..<endIndex])
        var mapy_jsonString = MIUAES.miuaesDecrypt(mapy_responseString, mode: MIUMode.init(1), key: mapy_vpn_dKey, keySize: MIUKeySizeAES.init(16), iv: nil, padding: MIUCryptorPadding.init(1))
        mapy_jsonString = mapy_jsonString.replacingOccurrences(of: "'", with: "\"")
        mapy_jsonString = mapy_jsonString.replacingOccurrences(of: "None", with: "null")
        guard let mapy_model = MAPYVPNRequestModel(JSONString: mapy_jsonString) else {
            return MAPYVPNRequestModel()
        }
        return mapy_model
    }
    
}
